package com.linkage.educloud.ah.widget;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.ClazzContact;
import com.linkage.educloud.ah.bean.ClazzGroup;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.data.Ws;
import com.linkage.educloud.ah.util.FaceUtils;
import com.linkage.educloud.ah.util.ImageLoader;
import com.zzhou.common.library.util.DateUtils;
import com.zzhou.common.library.util.LogUtils;
import com.zzhou.common.library.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
 * Created by The Moss on 2017/3/3.
 */

public class ChatItemView extends LinearLayout {
    private Context mContext;
    private Resources resources;
    private MyApplication mApp;
    private AccountData accountData;

    private ImageView mAvatar;
    private TextView mUnreadNum;
    private TextView mBuddyName;
    private TextView mSubName;
    private TextView mMsgContent;
    private TextView mDate;

    private int mBuddyIdColumn;
    private int mBodyColumn;
    private int mReceiveTimeColumn;
    private int mSendTimeColumn;
    private int mOutBoundColumn;
    private int mInBoundColumn;
    private int mMsgTypeColumn;
    private int mChatTypeColumn;
    private int mThreadTypeColumn;
    private int mUnreadColumn;

    public ChatItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        resources = getResources();
        mApp = MyApplication.getInstance();
        accountData = AccountConfig.getLoginAccount();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mAvatar = findViewById(R.id.chatitem_avatar);
        mUnreadNum = findViewById(R.id.chatitem_unread_count);
        mBuddyName = findViewById(R.id.chatitem_buddy_name);
        mSubName = findViewById(R.id.chatitem_sub_name);
        mMsgContent = findViewById(R.id.chatitem_msg_text);
        mDate = findViewById(R.id.chatitem_date);
    }

    public void init(Cursor cursor) {
        mBuddyIdColumn = cursor.getColumnIndex(Ws.ThreadTable.BUDDY_ID);
        mBodyColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_BODY);
        mReceiveTimeColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_RECEIVED_TIME);
        mSendTimeColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_SENT_TIME);
        mOutBoundColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_OUTBOUND_STATUS);
        mInBoundColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_IS_INBOUND);
        mMsgTypeColumn = cursor.getColumnIndex(Ws.ThreadTable.MSG_TYPE);
        mChatTypeColumn = cursor.getColumnIndex(Ws.ThreadTable.CHAT_TYPE);
        mThreadTypeColumn = cursor.getColumnIndex(Ws.ThreadTable.THREAD_TYPE);
        mUnreadColumn = cursor.getColumnIndex(Ws.ThreadTable.UNREAD_COUNT);
    }

    public void bindView(Cursor cursor) {
        ImageView avatarImage = mAvatar;
        TextView title = mBuddyName;
        TextView unRead = mUnreadNum;
        TextView subTitle = mSubName;
        TextView msgContent = mMsgContent;
        TextView date = mDate;

        String buddyId = cursor.getString(mBuddyIdColumn);
        String msg = cursor.getString(mBodyColumn);
        int unreadcount = cursor.getInt(mUnreadColumn);
        int chatType = cursor.getInt(mChatTypeColumn);
        int msgType = cursor.getInt(mMsgTypeColumn);

        subTitle.setVisibility(View.GONE);
        LogUtils.d("ChatItemView, ***************chattype = "+chatType+"**********************");
        switch (chatType) {
            case Constants.ChatType.CHAT_TYPE_SINGLE:
                LogUtils.d("ChatItemView, init one single");
                switch (msgType) {
                    case Ws.MessageType.TYPE_MSG_TEXT:
                        msgContent.setText(FaceUtils.replaceFaceSmall(mContext, msg));
                        break;
                    case Ws.MessageType.TYPE_MSG_PIC:
                        msgContent.setText("图片");
                        break;
                    case Ws.MessageType.TYPE_MSG_AUDIO:
                        msgContent.setText("语音");
                        break;
                }
                if (StringUtil.isNullOrEmpty(buddyId)) {
                    mApp.getResovler().clearIMMessages(accountData.getLoginAccount(), buddyId);
                    title.setText(buddyId + "");
                    avatarImage.setImageResource(R.mipmap.ic_default_avatar);
                    LogUtils.e("ChatItemView, sigle chat, invalid buddyId! buddyId="
                            + buddyId);
                } else {
                    long userid = -1;
                    LogUtils.d("ChatItemView, ************ init one single");
                    try {
                        ClazzContact contact = mApp.getResovler().getContactById(accountData.getLoginAccount(), userid+"",1);
                        if (contact != null) {
                            title.setText(contact.getName());
                            ImageLoader.loadAvatar(mContext,contact.getAvatar_url(),avatarImage);
                        } else {
                            mApp.getResovler().clearIMMessages(accountData.getLoginAccount(), buddyId);
                            title.setText(buddyId + "");
                            avatarImage.setImageResource(R.mipmap.group_avatar);
                            return;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        title.setText(buddyId + "");
                        avatarImage.setImageResource(R.mipmap.group_avatar);
                        LogUtils.e("ChatItemView, sigle chat, invalid userid! buddyId="
                                + buddyId);
                    }
                }
                break;
            case Constants.ChatType.CHAT_TYPE_GROUP:
                if (StringUtil.isNullOrEmpty(msg)) {
                    msgContent.setText(resources.getString(R.string.group_chat_tips));
                } else {
                    switch (msgType) {
                        case Ws.MessageType.TYPE_MSG_TEXT:
                            msgContent.setText(FaceUtils.replaceFaceSmall(mContext, msg));
                            break;
                        case Ws.MessageType.TYPE_MSG_PIC:
                            msgContent.setText("图片");
                            break;
                        case Ws.MessageType.TYPE_MSG_AUDIO:
                            msgContent.setText("语音");
                            break;
                    }
                }
                if (StringUtil.isNullOrEmpty(buddyId)) {
                    title.setText(buddyId + "");
                    avatarImage.setImageResource(R.mipmap.group_avatar);
                    LogUtils.e("ChatItemView, group chat, invalid buddyId! buddyId="
                            + buddyId);
                } else {
                    LogUtils.d("ChatItemView, init one group");
//                    long groupid = -1;
                    try {
//                        groupid = Long.parseLong(buddyId);
                        ClazzGroup group = mApp.getResovler().getGroupById(accountData.getLoginAccount(), buddyId);
                        if (group != null) {
                            title.setText(resources.getString(R.string.classchat));
                            subTitle.setVisibility(View.VISIBLE);
                            subTitle.setText(group.school_name + group.group_name);
                            avatarImage.setBackgroundResource(R.mipmap.group_avatar_self);
                        } else {
                            mApp.getResovler().clearIMMessages(accountData.getLoginAccount(), buddyId);
                            title.setText(resources.getString(R.string.classchat));
                            avatarImage.setImageResource(R.mipmap.group_avatar);
                            LogUtils.e("ChatItemView, group chat, invalid userid! buddyId="
                                    + buddyId);
                            break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        title.setText(resources.getString(R.string.classchat));
                        avatarImage.setImageResource(R.mipmap.group_avatar);
                        LogUtils.e("ChatItemView, group chat, invalid userid! buddyId="
                                + buddyId);
                    }
                }
                break;
            case Constants.ChatType.CHAT_TYPE_OTHER:
                LogUtils.d("ChatItemView, other chat start init msgType = " +msgType );
                switch (msgType) {
                    case Ws.MessageType.TYPE_CLASS_SPACE:
                        LogUtils.d("ChatItemView, init class space");
                        long groupid = -1;
                        try {
                                groupid = Long.parseLong(buddyId.substring(Constants.MESS_TYPE.APP_ID_SP.length(), buddyId.length()));
                                ClazzGroup group = mApp.getResovler().getGroupById(accountData.getLoginAccount(), String.valueOf(groupid));
                                if (group != null) {
                                    title.setText(resources.getString(R.string.classspace));
                                    subTitle.setVisibility(VISIBLE);
                                    subTitle.setText(group.school_name + group.group_name);
                                    avatarImage.setBackgroundResource(R.mipmap.campus_space);
                                } else {
                                    mApp.getResovler().clearIMMessages(accountData.getLoginAccount(), buddyId);
                                    title.setText(resources.getString(R.string.classspace));
                                    avatarImage.setImageResource(R.mipmap.campus_space);
                                    LogUtils.e("ChatItemView, classspace chat, invalid userid! buddyId="
                                            + buddyId);
                                    break;
                                }
                        } catch (Exception e) {
                            e.printStackTrace();
                            title.setText(resources.getString(R.string.classspace));
                            avatarImage.setImageResource(R.mipmap.campus_space);
                            LogUtils.e("ChatItemView, classspace chat, invalid userid! buddyId="
                                    + buddyId);
                        }
                        break;
                    case Ws.MessageType.TYPE_NEWS:
                        title.setText(resources.getString(R.string.news));
                        msgContent.setText(resources.getString(R.string.news_default_tips));
                        avatarImage.setImageResource(R.mipmap.campus_news);
                        break;
                    case Ws.MessageType.TYPE_TOPIC:
                        title.setText(resources.getString(R.string.topic));
                        msgContent.setText(resources.getString(R.string.topic_default_tips));
                        avatarImage.setImageResource(R.mipmap.circleicons);
                        break;
                }
                break;
        }
        // 日期
        if (msgType == Ws.MessageType.TYPE_MSG_TEXT
                || msgType == Ws.MessageType.TYPE_MSG_PIC
                || msgType == Ws.MessageType.TYPE_MSG_AUDIO) {
            int isInBound = cursor.getInt(mInBoundColumn);
            boolean inBound = isInBound == Ws.MessageType.INCOMING ? true
                    : false;
            long dateTime;
            if (inBound) {
                dateTime = cursor.getLong(mReceiveTimeColumn);
            } else {
                dateTime = cursor.getLong(mSendTimeColumn);
            }
            if (dateTime < 1) {
                date.setText("");
            } else {
                date.setText(setDateSpan(dateTime));
            }
            String sDateTime1 = DateUtils.getMMddFormat1(dateTime);
            String sDateTime = "";
            int index = sDateTime1.indexOf("-");
            if (sDateTime1.length() <= index) {
                date.setText("");
                LogUtils.e("###### strange datetime, sDateTime=" + sDateTime1);
            } else {
                sDateTime = sDateTime1.substring(0, index);
                if (isValid(sDateTime)) {
                    sDateTime = sDateTime1.substring(index + 1,
                            sDateTime1.length());
                    date.setText(sDateTime);
                    date.setVisibility(View.VISIBLE);
                } else {
                    date.setText("");
                }
            }
            if (chatType == Constants.ChatType.CHAT_TYPE_GROUP
                    && StringUtil.isNullOrEmpty(msg)) {
                date.setText("");
            }
        } else {
            date.setVisibility(View.GONE);
        }
        if (unreadcount <= 0) {
            unRead.setVisibility(View.GONE);
        } else {
            switch (msgType) {
                case Ws.MessageType.TYPE_MSG_TEXT:
                case Ws.MessageType.TYPE_MSG_PIC:
                case Ws.MessageType.TYPE_MSG_AUDIO:
                case Ws.MessageType.TYPE_NEWS:
                case Ws.MessageType.TYPE_JX:
                case Ws.MessageType.TYPE_CLASS_SPACE:
                    // unread_iv.setVisibility(View.VISIBLE);
                    // mUnreadCountView.setVisibility(View.GONE);
                    unRead.setVisibility(View.VISIBLE);
                    unRead.setBackgroundResource(R.mipmap.ic_unread_img);
                    if (unreadcount > 99) {
                        unRead.setText("99+");
                    } else {
                        unRead.setText(String.valueOf(unreadcount));
                    }
                    break;
            }
        }
    }

    private boolean isValid(String y) {

        boolean ret = false;

        try {
            int year = Integer.parseInt(y);
            if (year > 1970 && year < 9999) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }

    private Date getMsgDate(long dataVal) {
        Date msgDate = new Date(dataVal);
        try {
            // msgDate = DateUtils.FORMAT_FEED.parse(dataVal);
            // L.i("msgDateVal", "msgDateVal = " + msgDateVal);
        } catch (Exception e) {
            // msgDate = new Date(System.currentTimeMillis());
        }

        return msgDate;
    }

    private Calendar getMsgDateCalendar(long dataVal) {
        Calendar msgCal = Calendar.getInstance();
        msgCal.setTime(this.getMsgDate(dataVal));
        return msgCal;
    }

    private String setDateSpan(long dataVal) {
        // 取系统当前时间作为参照，判断消息是否是今天的
        Date currentDate = new Date(System.currentTimeMillis());
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(currentDate);
        currentCal.get(Calendar.DAY_OF_MONTH);
        Date msgDate = this.getMsgDate(dataVal);
        Calendar msgCal = this.getMsgDateCalendar(dataVal);
        msgCal.get(Calendar.DAY_OF_MONTH);

        StringBuffer sb = new StringBuffer();
        if (msgCal.get(Calendar.YEAR) != currentCal.get(Calendar.YEAR)) {
            sb.append(msgCal.get(Calendar.YEAR)).append("年");
            sb.append(this.getDateStringRemovedHeadingZero("MM月", msgDate));
            // .append(this.getDateString("dd  ", msgDate));
        } else {
            if (this.isSameDay(currentCal, msgCal)
                    && (msgCal.get(Calendar.YEAR) == currentCal
                    .get(Calendar.YEAR))) {
                sb.append("今天");
                sb.append(this.getDateString("HH:", msgDate)).append(
                        this.getDateString("mm", msgDate));
            } else {
                currentCal.add(Calendar.DATE, -1);// 设置时间为昨天
                if (this.isSameDay(currentCal, msgCal)) {
                    sb.append("昨天");
                    sb.append(this.getDateString("HH:", msgDate)).append(
                            this.getDateString("mm", msgDate));
                } else {
                    sb.append(
                            this.getDateStringRemovedHeadingZero("MM月", msgDate))
                            .append(this.getDateString("dd  ", msgDate));
                }
            }

        }
        return sb.toString();
    }

    private boolean isSameDay(Calendar formerCal, Calendar laterCal) {
        return (formerCal.get(Calendar.YEAR) == laterCal.get(Calendar.YEAR))
                && (formerCal.get(Calendar.MONTH) == laterCal
                .get(Calendar.MONTH))
                && (formerCal.get(Calendar.DAY_OF_MONTH) == laterCal
                .get(Calendar.DAY_OF_MONTH));
    }

    private String getDateStringRemovedHeadingZero(
            String simpleDateFormatPattern, Date date) {
        String dateStr = new SimpleDateFormat(simpleDateFormatPattern)
                .format(date);
        if (dateStr.startsWith("0"))
            dateStr = dateStr.substring(1);
        return dateStr;
    }

    private String getDateString(String simpleDateFormatPattern, Date date) {
        String dateStr = new SimpleDateFormat(simpleDateFormatPattern)
                .format(date);

        return dateStr;
    }
}
